package com.xincongjun.media.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.xincongjun.media.utils.DateTimeUtil.*;


public class ExifToolUtil {

    private static final Logger logger = LoggerFactory.getLogger(ExifToolUtil.class);

    public static void useExifToolUpdateTime(String filePath, String timeString, String timeZoneType, List<String> timeFields) {
        if (timeZoneType.equalsIgnoreCase(ZONE_UTC)) {
            timeString = DateTimeUtil.convertToTargetTimeZone(timeString, ZONE_LOCAL, ZONE_UTC, DateTimeUtil.STANDARD_TIME_PATTERN);
        }
        timeString = convertDateFormat(timeString, DateTimeUtil.STANDARD_TIME_PATTERN, DateTimeUtil.EXIF_TIME_PATTERN);

        List<String> command = new ArrayList<>();
        command.add("exiftool");

        if (timeFields == null || timeFields.isEmpty()) {
            command.add("-AllDates=" + timeString);
        } else {
            for (String field : timeFields) {
                field = field.trim();
                command.add(field + "=" + timeString);
            }
        }

        command.add("-overwrite_original");
        command.add(filePath);

        ProcessBuilder builder = new ProcessBuilder(command);
        builder.redirectErrorStream(true);

        try {
            Process process = builder.start();

            String output;
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.forName("GBK")))) {
                output = reader.lines().collect(Collectors.joining(System.lineSeparator()));
            }

            int exitCode = process.waitFor();
            if (exitCode != 0) {
                throw new RuntimeException("执行 ExifTool 命令失败：" + filePath + "\n" + output);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String useExifToolReadJpgOrMp4Time(String filePath) throws Exception {
        String dateTimeOriginal = "";
        ProcessBuilder builder = null;

        switch (FileUtil.getRealFileType(filePath)){
            case "jpg":
                builder = new ProcessBuilder("exiftool", "-ExifIFD:DateTimeOriginal", filePath);
                break;
            case "mp4":
                builder = new ProcessBuilder("exiftool", "-QuickTime:CreateDate", filePath);
                break;
        }

        if (builder == null) {
            logger.error("文件的真实类型不是 .jpg 或 .mp4：{}", filePath);
            return dateTimeOriginal;
        }

        builder.redirectErrorStream(true);

        try {
            Process process = builder.start();

            try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    if (line.startsWith("Date/Time Original") || line.startsWith("Create Date")) {
                        int colonIndex = line.indexOf(":");
                        if (colonIndex != -1 && colonIndex + 1 < line.length()) {
                            dateTimeOriginal = line.substring(colonIndex + 1).trim().toLowerCase();
                        }else{
                            logger.error("-ExifIFD:DateTimeOriginal 或：-ExifIFD:DateTimeOriginal 字段的值不存在：{}", filePath);
                            return dateTimeOriginal;
                        }
                    }else {
                        logger.error("文件不存在 -ExifIFD:DateTimeOriginal 或：-ExifIFD:DateTimeOriginal 字段：{}", filePath);
                        return dateTimeOriginal;
                    }
                }
            }
            process.waitFor();
        }catch (Exception e){
            e.printStackTrace();
        }

        return dateTimeOriginal;
    }

}